// components/cz-calender/cz-calender.js
import {
  Slide
} from './func/utils';
const slide = new Slide();
Component({

  options: {
    pureDataPattern: /^_/ // 指定所有 _ 开头的数据字段为纯数据字段
  },
  /**
   * 组件的属性列表
   */
  properties: {
    isHide: {
      type: Boolean,
      value: false
    },
    currentDate: {
      type: String,
      value: '',
      observer: function (newVal, oldVal) {
        if (newVal) {
			console.log('current data-------------',newVal)
          newVal = newVal.replace(/-/g, "/")
          let date = new Date(newVal)
          this.getCurrentDate(date)
        }
      }
    },
    taskList: {
      type: Array,
      value: [],
      observer: function (newVal, oldVal) {
		  // console.log('task list ------------------',newVal,newVal.length)
		  // newVal.map(item=>{
			 //  console.log('fetch--------------',item,item.completeStatus,item.yearMonthDay)
		  // })
        if (newVal.length == 0) {
          if (this.data.currentMonth == 0) {
            const date = new Date();
            this.setData({
              year: date.getFullYear(),
              lastMonth: date.getMonth(),
              currentMonth: date.getMonth() + 1,
              nextMonth: (date.getMonth() + 2) > 12 ? 1 : date.getMonth() + 2,
            })
            this.getCurrentDate(date)
            this.data._monthNum = this.getMonthNumber(date.getFullYear(), date.getMonth() + 1);
            this.getWeek(date.getFullYear(), date.getMonth() + 1, 1);
            this.setCalendarData();
          }
          return
        }
        if (this.properties.isHide) {
          let currentMonth, lastMonth, nextMonth, year
          newVal.forEach((item, index) => {
            if (item.completeStatus != 3) {
              currentMonth = parseInt(newVal[index].yearMonthDay.substring(5, 7))
              lastMonth = newVal[index].yearMonthDay.substring(5, 7) == '01' ? 12 : parseInt(newVal[index].yearMonthDay.substring(5, 7)) - 1
              nextMonth = newVal[index].yearMonthDay.substring(5, 7) == '01' ? 12 : parseInt(newVal[index].yearMonthDay.substring(5, 7)) + 1
              year = parseInt(newVal[index].yearMonthDay.substring(0, 4))
            }
          });

          this.setData({
            currentMonth: currentMonth,
            lastMonth: lastMonth,
            nextMonth: nextMonth,
            year: year,
          })
        } else {//最先进入这里
          this.setData({
            currentMonth: parseInt(newVal[0].yearMonthDay.substring(5, 7)),
            lastMonth: newVal[0].yearMonthDay.substring(5, 7) == '01' ? 12 : parseInt(newVal[0].yearMonthDay.substring(5, 7)) - 1,
            nextMonth: parseInt(newVal[0].yearMonthDay.substring(5, 7)) == 12 ? 1 : parseInt(newVal[0].yearMonthDay.substring(5, 7)) + 1,
            year: parseInt(newVal[0].yearMonthDay.substring(0, 4)),
          })
        }
        console.log('asda-----', this.data.currentMonth)
        console.log('asda-----', this.data.lastMonth)
        console.log('asda-----', this.data.nextMonth)
        console.log('asda-----', this.data.year)
        let month = this.data.currentMonth
        this.data._monthNum = this.getMonthNumber(this.data.year, month)
        this.getWeek(this.data.year, month, 1)
        this.setCalendarData()
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    isWeek: false,
    activeWeekIndex: 0,
    activeIndex: 0,
    _taskList: [],
    _monthNum: 0,
    firstWeek: 0,
    dayList: [],
    lastMonth: 0,
    nextMonth: 0,
    currentMonth: 0,
    year: 0,
    selectIndex: -1,
    selectPIndex: -1,
    selectMonth: -1,
    selectYear: -1,
    taskId: -1,
    _currentMonth: '',
    weekMonth: '', //周视图月份
    weekYear: '', //周视图年份
    weekList: [{
        activeWeekIndex: 0,
        date: '日',
        item: {}
      },
      {
        activeWeekIndex: 1,
        date: '一',
        item: {}
      },
      {
        activeWeekIndex: 2,
        date: '二',
        item: {}
      },
      {
        activeWeekIndex: 3,
        date: '三',
        item: {}
      },
      {
        activeWeekIndex: 4,
        date: '四',
        item: {}
      },
      {
        activeWeekIndex: 5,
        date: '五',
        item: {}
      },
      {
        activeWeekIndex: 6,
        date: '六',
        item: {}
      }
    ],
  },



  // 此处attached的声明会被lifetimes字段中的声明覆盖
  attached() {
    // console.log(date.getDate())
    // this.setData({
    //   year: date.getFullYear(),
    //   lastMonth: date.getMonth(),
    //   currentMonth: date.getMonth() + 1,
    //   nextMonth: date.getMonth() + 2,
    // })
    const date = new Date();
    this.getCurrentDate(date)
    // this.data._monthNum = this.getMonthNumber(date.getFullYear(), date.getMonth() + 1);
    // this.getWeek(date.getFullYear(), date.getMonth() + 1, 1);
    // this.setCalendarData();
  },


  /**
   * 组件的方法列表
   */
  methods: {
    getCurrentDate(date) {
      let year = date.getFullYear()
      let month = date.getMonth() < 9 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
      let day = date.getDate() < '10' ? '0' + date.getDate() : date.getDate()
      this.setData({
        currentDate: year + '-' + month + '-' + day
      })
      console.log('date.getDate()--', this.data.currentDate)
      this.data._currentMonth = year + '' + month
      this.data.weekYear = date.getFullYear()
      this.data.weekMonth = date.getMonth() + 1
    },
    expandClick() {
      this.data.isWeek = this.data.isWeek ? false : true
      this.setData({
        isWeek: this.data.isWeek
      })
    },
    selectCurrent(e) {
      let data = e.currentTarget.dataset
      console.log('asd------', data)
      if (data.status == -1 || data.item.showStatus == -1) {
        let day = e.currentTarget.dataset.item.day
        if (!this.data.isWeek || this.data.isHide) {
          if (day < 10) {
            this.onNextClick()
          } else {
            this.onLastClick()
          }
        }
        return
      }
      if (this.data.isWeek) {
        console.log(e)
        e.currentTarget.dataset.date = e.currentTarget.dataset.item.date
        this.setData({
          activeWeekIndex: e.currentTarget.dataset.index
        })
      } else {
        this.setData({
          activeIndex: data.date
        })
      }
      let dateSelect = e.currentTarget.dataset.date
      let indexWeek = 0
      let activeWeekIndex = 0
      let activeIndex = 0
      this.data.dayList.forEach((item, index) => {
        item.forEach((itemChild, childIndex) => {
          if (dateSelect == itemChild.date) {
            indexWeek = index
            activeWeekIndex = childIndex
            activeIndex = itemChild.date
          }
        })
      })
      this.data.dayList[indexWeek].forEach((item, index) => {
        this.data.weekList[index].item = item
      })
      this.setData({
        weekList: this.data.weekList,
        dayList: this.data.dayList,
        activeIndex: activeIndex,
        activeWeekIndex: activeWeekIndex
      })
      this.triggerEvent('onCalendarItemClick', e.currentTarget.dataset)
    },
    /**
     * 日历滑动开始
     * @param {object} e
     */
    calendarTouchstart(e) {
      const t = e.touches[0];
      const startX = t.clientX;
      const startY = t.clientY;
      this.slideLock = true; // 滑动事件加锁
      this.setData({
        'gesture.startX': startX,
        'gesture.startY': startY
      });
    },
    /**
     * 日历滑动中
     * @param {object} e
     */
    calendarTouchmove(e) {
      const {
        gesture
      } = this.data;
      if (!this.slideLock) return;
      if (slide.isLeft(gesture, e.touches[0])) {
        this.handleSwipe('left');
        this.slideLock = false;
      }
      if (slide.isRight(gesture, e.touches[0])) {
        this.handleSwipe('right');
        this.slideLock = false;
      }
    },
    handleSwipe(direction) {
      if (direction === 'right') {
        this.onLastClick()
      } else {
        this.onNextClick()
      }
    },
    calendarTouchend(e) {},

    onLastClick() {
      let tempMonth = this.data.lastMonth - 1
      if (this.data.lastMonth <= 1) {
        tempMonth = 12
      }
      if (this.data.currentMonth == 1) {
        this.data.year--
      }
      let month = this.data.currentMonth
      if (month <= 1) {
        month = 12
      } else {
        month--
      }
      this.setData({
        currentMonth: this.data.lastMonth,
        nextMonth: this.data.currentMonth,
        year: this.data.year,
        lastMonth: tempMonth,
      })

      this.data._monthNum = this.getMonthNumber(this.data.year, month);
      this.getWeek(this.data.year, month, 1);
      this.setCalendarData();
      let dateMonth = month < 10 ? '0' + month : month
      if (parseInt(this.data.year + '' + dateMonth) <= parseInt(this.data._currentMonth)) {
        let date = this.data.year + '-' + dateMonth
        this.triggerEvent('monthChange', date)
      }
    },

    onNextClick() {
      let tempMonth = this.data.nextMonth + 1
      if (this.data.nextMonth >= 12) {
        tempMonth = 1
      }
      if (this.data.currentMonth == 12) {
        this.data.year++
      }
      let month = this.data.currentMonth
      if (month >= 12) {
        month = 1
      } else {
        month++
      }
      this.setData({
        currentMonth: month,
        lastMonth: this.data.currentMonth,
        year: this.data.year,
        nextMonth: tempMonth,
      })
      this.data._monthNum = this.getMonthNumber(this.data.year, month);
      this.getWeek(this.data.year, month, 1);
      this.setCalendarData();
      let dateMonth = month < 10 ? '0' + month : month
      if (parseInt(this.data.year + '' + dateMonth) <= parseInt(this.data._currentMonth)) {
        let date = this.data.year + '-' + dateMonth
        this.triggerEvent('monthChange', date)
      }
    },
    setCalendarData() {
      this.data.dayList = []
      let itemChild = {
        index: 0,
        day: 0,
        date: 0,
        showStatus: '0',
        taskName: '',
        taskId: '',
        mendTime: '',
        createTime: '',
        taskIndex: '',
        isSpecial: '',
        isEnd: 0,
		inSta:0,
		outSta:0
      }
      for (let i = 0; i < 6; i++) {
        let item = []
        for (let j = 0; j < 7; j++) {
          itemChild.index = j * i
          item.push(itemChild);
        }
        this.data.dayList.push(item)
      }
      console.log('bbbbbbbbbbbbbccccccccccccccccccccbbbb----', this.data._monthNum)
      for (let i = 0, k = 1; i < 6; i++) {
        for (let j = 0; j < 7; j++) {
          if (i == 0 && j < this.data.firstWeek) {
            let itemChild = {
              day: 0,
              date: '',
              showStatus: '-1',
              taskName: '',
              taskId: '',
              mendTime: '',
              createTime: '',
              taskIndex: '',
              isSpecial: '',
              isEnd: 0,
			  inSta:0,
			  outSta:0
            }
            itemChild.day = 0
            console.log('this._taskList.dayList[i][j] ----', itemChild)
            this.data.dayList[i][j] = itemChild;
            console.log('this._taskList.dayList[i][j] ----', this.data.dayList[i][j])
            continue
          }
          if (k <= this.data._monthNum) {
            let time = this.data.year + ''
            let month = this.data.currentMonth + ''
            let tempK = k + ''
            if (k < 10) {
              tempK = '0' + tempK
            }
            if (this.data.currentMonth < 10) {
              month = '0' + month
            }
            time = time + '-' + month + '-' + tempK
            let itemChild = {
              day: k,
              date: time,
              showStatus: '0',
              taskName: '',
              taskId: '',
              mendTime: '',
              createTime: '',
              taskIndex: '',
              isSpecial: '',
              isEnd: 0,
			  inSta:0,
			  outSta:0
            }
            this.data.dayList[i][j] = itemChild;
            k++;
          } else {
            let itemChild = {
              day: 0,
              date: '',
              showStatus: '-1',
              taskName: '',
              taskId: '',
              mendTime: '',
              createTime: '',
              taskIndex: '',
              isSpecial: '',
              isEnd: 0,
			  inSta:0,
			  outSta:0
            }
            this.data.dayList[i][j] = itemChild;
            k = 42
          }
        }
      }
      let temp = this.data.dayList
      console.log('bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb----', temp)
      this.data._taskList = this.properties.taskList
	  // const today = new Date()
	  // const ty = today.getFullYear();
	  // const tm = ('0' + (today.getMonth() + 1)).slice(-2);
	  // const td = ('0' + today.getDate()).slice(-2);
	  // const dateStr = ty+'-'+tm+'-'+td
	  // console.log('7777777777777777777--------',this.properties.taskList)
      this.data._taskList.forEach((itemJ,indexJ)=> {
        this.data.dayList.forEach((item, index) => {
          let isDelete = true
          item.forEach((itemChild, childIndex) => {
            if (itemChild.day != 0) {
              isDelete = false
            }
            if (itemChild.date == itemJ.yearMonthDay) {
              itemChild.showStatus = itemJ.showStatus
              itemChild.taskName = itemJ.taskName
              itemChild.taskId = itemJ.taskId
              itemChild.isEnd = itemJ.isEnd
              if (itemJ.mendTime) {
                itemChild.mendTime = itemJ.mendTime
              }
              if (itemJ.createTime) {
                itemChild.createTime = itemJ.createTime
              }
              if (itemJ.createTime) {
                itemChild.createTime = itemJ.createTime
              }
              if (itemJ.taskIndex) {
                itemChild.taskIndex = itemJ.taskIndex
              }
              if (itemJ.isSpecial) {
                itemChild.isSpecial = itemJ.isSpecial
              }
            }
			if (itemChild.date == itemJ.yearMonthDay) {
				itemChild.inSta = 5
			}
			// itemJ.completeStatus = 1
			if (itemChild.date == itemJ.yearMonthDay && itemJ.completeStatus>0) {
				//内部肯定亮
				itemChild.inSta = 1
				//外部如何点亮，4种情况，左圆右方1，都方2，左方右圆3，不亮
				if (childIndex===0 && this.data._taskList[indexJ+1]?.completeStatus>0) {
					itemChild.outSta = 1
				}else if (childIndex===6 && this.data._taskList[indexJ-1]?.completeStatus>0) {
					itemChild.outSta = 3
				}else if (childIndex>0 && childIndex<6) {
					if (this.data._taskList[indexJ-1]?.completeStatus>0 && this.data._taskList[indexJ+1]?.completeStatus>0) {
						itemChild.outSta = 2
					} else if (this.data._taskList[indexJ+1]?.completeStatus>0 && !this.data._taskList[indexJ-1]?.completeStatus) {
						itemChild.outSta = 1
					} else if (this.data._taskList[indexJ-1]?.completeStatus>0 && !this.data._taskList[indexJ+1]?.completeStatus) {
						itemChild.outSta = 3
					}
				}
			}
          })
          if (isDelete) {
            this.data.dayList.splice(index, 1)
          }
        })
      })
      if (this.data._taskList.length == 0) {
        this.data.dayList.forEach((item, index) => {
          let isDelete = true
          item.forEach((itemChild, childIndex) => {
            if (itemChild.day != 0) {
              isDelete = false
            }
          })
          if (isDelete) {
            this.data.dayList.splice(index, 1)
          }
        })
      }
      let lastMonth, lastDay
      if (this.data.currentMonth == 1) {
        lastMonth = 12
        lastDay = this.getMonthNumber(this.data.year - 1, lastMonth)
      } else {
        lastMonth = this.data.currentMonth - 1
        lastDay = this.getMonthNumber(this.data.year, lastMonth)
      }
      console.log(this.data.dayList)
      for (let i = this.data.dayList[0].length - 1; i >= 0; i--) {
        if (this.data.dayList[0][i].day == 0) {
          this.data.dayList[0][i].day = lastDay
          lastDay--
        }
      }
      let day = 1
      for (let i = 0; i < this.data.dayList[this.data.dayList.length - 1].length; i++) {
        if (this.data.dayList[this.data.dayList.length - 1][i].day == 0) {
          this.data.dayList[this.data.dayList.length - 1][i].day = day
          day++
        }
      }

      if (this.data.weekYear == this.data.year && this.data.currentMonth == this.data.weekMonth) {
        console.log('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')
        let indexWeek = 0
        let activeWeekIndex = 0
        let activeIndex = 0
        this.data.dayList.forEach((item, index) => {
          item.forEach((itemChild, childIndex) => {
            if (this.data.currentDate == itemChild.date) {
              indexWeek = index
              activeWeekIndex = childIndex
              activeIndex = this.data.activeIndex ? this.data.activeIndex : itemChild.date
            }
          })
        })
        this.data.dayList[indexWeek].forEach((item, index) => {
          this.data.weekList[index].item = item
        })
        this.setData({
          weekList: this.data.weekList,
          activeIndex: activeIndex,
          activeWeekIndex: activeWeekIndex
        })
      }
      console.log('this.data.dayList----', this.data.dayList)
      this.setData({
        dayList: this.data.dayList,
      })
    },
    getWeek(year_local, month_local, day_local) {
      let str = year_local + '/' + month_local + '/' + day_local
      let week = new Date(str);
      console.log('y----', week.getDay())
      console.log('y----', year_local)
      console.log('m----', month_local)
      console.log('d----', day_local)
      let week_output = 0;
      switch (parseInt(week.getDay())) {
        case 0:
          this.setData({
            firstWeek: 0
          })
          break;
        case 1:
          this.setData({
            firstWeek: 1
          })
          break;
        case 2:
          this.setData({
            firstWeek: 2
          })
          break;
        case 3:
          this.setData({
            firstWeek: 3
          })
          break;
        case 4:
          this.setData({
            firstWeek: 4
          })
          break;
        case 5:
          this.setData({
            firstWeek: 5
          })
          break;
        case 6:
          this.setData({
            firstWeek: 6
          })
          break;
        default:
          console.log("Error");
          break;
      }
    },

    getMonthNumber(year, month) {
      console.log("month", month);
      let monthNum = 0
      if (year > 0) {
        if (month > 0 && month < 13) {
          switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
              monthNum = 31
              break;
            case 2:
              if (year % 400 == 0 || year % 100 != 0 && year % 4 == 0) {
                monthNum = 29
              } else {
                monthNum = 28
              }
              break;
            case 4:
            case 6:
            case 9:
            case 11:
              monthNum = 30
              break;
          }
        }
      }
      return monthNum
    }
  }
})